#define _CRT_SECURE_NO_WARNINGS 1

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;

int n, m;
int a[N][N];
bool st[N][N];

int dx[] = { 0, 0, 1, -1 };
int dy[] = { 1, -1, 0, 0 };

bool bfs(int mid)
{
    if (n == 1) return true;
    memset(st, 0, sizeof st);

    queue<PII> q;

    for (int j = 1; j <= m; j++)
    {
        q.push({ 1, j });
        st[1][j] = true;
    }

    while (q.size())
    {
        auto t = q.front(); q.pop();
        int x = t.first, y = t.second;
        for (int i = 0; i < 4; i++)
        {
            int a = x + dx[i], b = y + dy[i];
            if (a >= 1 && a <= n && b >= 1 && b <= m && a[a][b] <= mid && st[a]
                [b] == false)
            {
                st[a][b] = true;
                q.push({ a, b });
                if (a == n) return true;
            }
        }
    }

    return false;
}

int main()
{
    cin >> n >> m;
    int l = 0, r = 0;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            cin >> a[i][j];
            r = max(r, a[i][j]);
        }
    }

    while (l < r)
    {
        int mid = (l + r) / 2;
        if (bfs(mid)) r = mid;
        else l = mid + 1;
    }
    cout << l << endl;
    return 0;
}
